// 本地有约 - 主JavaScript文件

$(document).ready(function() {
    // CSRF Token设置
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    const csrftoken = getCookie('csrftoken');
    
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    
    // 活动报名
    $('.btn-register-activity').click(function(e) {
        e.preventDefault();
        const activityId = $(this).data('activity-id');
        const btn = $(this);
        
        $.post(`/activities/${activityId}/register/`, function(data) {
            if (data.success) {
                btn.removeClass('btn-primary').addClass('btn-secondary');
                btn.text('已报名');
                btn.prop('disabled', true);
                showAlert('success', data.message);
                location.reload();
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    // 取消报名
    $('.btn-unregister-activity').click(function(e) {
        e.preventDefault();
        if (!confirm('确定要取消报名吗？')) return;
        
        const activityId = $(this).data('activity-id');
        
        $.post(`/activities/${activityId}/unregister/`, function(data) {
            if (data.success) {
                showAlert('success', data.message);
                location.reload();
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    // 活动签到
    $('.btn-checkin').click(function(e) {
        e.preventDefault();
        const activityId = $(this).data('activity-id');
        
        $.post(`/activities/${activityId}/checkin/`, function(data) {
            if (data.success) {
                showAlert('success', data.message);
                location.reload();
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    // 评分活动
    $('.rating-star').click(function() {
        const score = $(this).data('score');
        const activityId = $(this).data('activity-id');
        
        $.post(`/activities/${activityId}/rate/`, {score: score}, function(data) {
            if (data.success) {
                showAlert('success', data.message);
                $('.average-rating').text(data.average_rating);
                updateStars(score);
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    function updateStars(score) {
        $('.rating-star').each(function(index) {
            if (index < score) {
                $(this).removeClass('bi-star').addClass('bi-star-fill');
            } else {
                $(this).removeClass('bi-star-fill').addClass('bi-star');
            }
        });
    }
    
    // 发表评论
    $('#comment-form').submit(function(e) {
        e.preventDefault();
        const form = $(this);
        const content = form.find('[name="content"]').val();
        const activityId = form.data('activity-id');
        
        $.post(`/activities/${activityId}/comment/`, {content: content}, function(data) {
            if (data.success) {
                form.find('[name="content"]').val('');
                showAlert('success', '评论发表成功');
                location.reload();
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    // 点赞评论
    $('.btn-like-comment').click(function(e) {
        e.preventDefault();
        const commentId = $(this).data('comment-id');
        const btn = $(this);
        
        $.post(`/activities/comment/${commentId}/like/`, function(data) {
            if (data.success) {
                btn.find('.likes-count').text(data.likes_count);
                if (data.action === 'liked') {
                    btn.find('i').removeClass('bi-heart').addClass('bi-heart-fill');
                } else {
                    btn.find('i').removeClass('bi-heart-fill').addClass('bi-heart');
                }
            }
        });
    });
    
    // 关注用户
    $('.btn-follow').click(function(e) {
        e.preventDefault();
        const userId = $(this).data('user-id');
        const btn = $(this);
        
        $.post(`/social/follow/${userId}/`, function(data) {
            if (data.success) {
                btn.removeClass('btn-primary').addClass('btn-secondary');
                btn.html('<i class="bi bi-person-check"></i> 已关注');
                showAlert('success', data.message);
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    // 取消关注
    $('.btn-unfollow').click(function(e) {
        e.preventDefault();
        const userId = $(this).data('user-id');
        const btn = $(this);
        
        $.post(`/social/unfollow/${userId}/`, function(data) {
            if (data.success) {
                btn.removeClass('btn-secondary').addClass('btn-primary');
                btn.html('<i class="bi bi-person-plus"></i> 关注');
                showAlert('success', data.message);
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    // 发送私信
    $('#message-form').submit(function(e) {
        e.preventDefault();
        const form = $(this);
        const content = form.find('[name="content"]').val();
        const userId = form.data('user-id');
        
        $.post(`/social/messages/send/${userId}/`, {content: content}, function(data) {
            if (data.success) {
                form.find('[name="content"]').val('');
                appendMessage(data.message, true);
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    function appendMessage(message, isSent) {
        const messageHtml = `
            <div class="message-bubble ${isSent ? 'sent' : 'received'} mb-3">
                <div class="message-content p-3 rounded">
                    ${message.content}
                </div>
                <small class="text-muted">${message.created_at}</small>
            </div>
        `;
        $('.messages-container').append(messageHtml);
        $('.messages-container').scrollTop($('.messages-container')[0].scrollHeight);
    }
    
    // 兑换奖品
    $('.btn-exchange-reward').click(function(e) {
        e.preventDefault();
        if (!confirm('确定要兑换此奖品吗？')) return;
        
        const rewardId = $(this).data('reward-id');
        
        $.post(`/points/shop/${rewardId}/exchange/`, function(data) {
            if (data.success) {
                showAlert('success', data.message);
                setTimeout(() => location.reload(), 1500);
            } else {
                showAlert('danger', data.message);
            }
        });
    });
    
    // 获取用户位置
    $('#btn-get-location').click(function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                loadNearbyActivities(lat, lng);
            }, function(error) {
                showAlert('danger', '无法获取您的位置');
            });
        } else {
            showAlert('danger', '您的浏览器不支持地理定位');
        }
    });
    
    function loadNearbyActivities(lat, lng) {
        $.get(`/activities/nearby/?lat=${lat}&lng=${lng}`, function(data) {
            if (data.success) {
                displayNearbyActivities(data.activities);
            } else {
                showAlert('danger', data.message);
            }
        });
    }
    
    function displayNearbyActivities(activities) {
        const container = $('#nearby-activities');
        container.empty();
        
        if (activities.length === 0) {
            container.html('<p class="text-muted">附近暂无活动</p>');
            return;
        }
        
        activities.forEach(activity => {
            const html = `
                <div class="card mb-3">
                    <div class="card-body">
                        <h5 class="card-title">${activity.title}</h5>
                        <p class="card-text">
                            <i class="bi bi-geo-alt"></i> ${activity.location}
                            <span class="badge bg-primary">${activity.distance}km</span>
                        </p>
                        <a href="/activities/${activity.id}/" class="btn btn-sm btn-primary">查看详情</a>
                    </div>
                </div>
            `;
            container.append(html);
        });
    }
    
    // 显示提示消息
    function showAlert(type, message) {
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('.container').first().prepend(alertHtml);
        
        setTimeout(() => {
            $('.alert').fadeOut();
        }, 3000);
    }
    
    // 图片预览
    $('input[type="file"]').change(function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $(this).siblings('.image-preview').attr('src', e.target.result).show();
            }.bind(this);
            reader.readAsDataURL(file);
        }
    });
    
    // 自动隐藏提示消息
    setTimeout(() => {
        $('.alert').fadeOut();
    }, 5000);
});
